package com.grant.code.controller;

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifIFD0Directory;
import com.grant.code.utils.DialogUtils;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Slider;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.ScrollEvent;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Set;

public class ImagerViewerController {
    @FXML public Button SlideShowButton;
    @FXML private Slider ScaleSlider;
    //图片拖拽
    private double dragStartX;
    private double dragStartY;
    private double initialTranslateX;
    private double initialTranslateY;

    private File currentImageFile;
    private List<File> imageList;
    private int currentIndex;
    private final Set<String> SUPPORTED_FORMATS = Set.of(".jpg", ".jpeg", ".png", ".gif", ".bmp");

    @FXML
    private Label pageInfo; // 页数

    @FXML
    private ImageView imageView;

    @FXML
    private Timeline slideTimeline;

    // 添加缺失的成员变量
    @FXML
    private Label photoName; // 添加 photoName 变量

    private double scaleFactor = 1.0; // 添加 scaleFactor 变量

    @FXML
    private ScrollPane scrollPane; // 添加 scrollPane 变量


    @FXML
    public void initialize() {
        ScaleSlider.setMin(0.1);
        ScaleSlider.setMax(5.0);
        ScaleSlider.setValue(1.0);
        ScaleSlider.valueProperty().addListener((obs, oldVal, newVal) -> {
            scaleFactor = newVal.doubleValue();
            imageView.setScaleX(scaleFactor);
            imageView.setScaleY(scaleFactor);
        });

        updatePageInfo();
    }


    public void setImageList(List<File> images, int currentIndex) {
        // 直接使用传入的图片列表，不要再次替换
        this.imageList = images;
        this.currentIndex = currentIndex;

        // 设置当前图片
        if (!images.isEmpty() && currentIndex >= 0 && currentIndex < images.size()) {
            this.currentImageFile = images.get(currentIndex);
            loadImage();
        }
    }

    // 重构后的 loadImage 方法
    private void loadImage() {
        try {
            if (currentImageFile == null || !currentImageFile.exists()) {
                throw new FileNotFoundException("文件不存在：" + currentImageFile);
            }

            // 检查文件格式
            String ext = getFileExtension(currentImageFile.getName()).toLowerCase();
            if (!SUPPORTED_FORMATS.contains(ext)) {
                throw new IllegalArgumentException("不支持的图片格式：" + ext);
            }

        // 加载图片
            Image image = new Image(currentImageFile.toURI().toString(), true);
            imageView.setImage(image);

        // 处理 EXIF 方向
            int orientation = getImageOrientation(currentImageFile);
            applyOrientationRotation(orientation);

            // 重置缩放
            resetZoom();

            // 显示文件名
            photoName.setText(currentImageFile.getName());
            // 绑定鼠标事件
            setupDragHandlers();

            // 在加载完成后更新页数
            Platform.runLater(this::updatePageInfo);

        } catch (Exception e) {
            DialogUtils.showErrorDialog("加载失败",
                    String.format("图片加载失败：%s%n%s", currentImageFile.getName(), e.getMessage()));
            e.printStackTrace();
        }
    }

    // 设置鼠标拖拽事件
    private void setupDragHandlers() {
        imageView.setOnMousePressed(event -> {
            if (event.isPrimaryButtonDown()) {
                // 记录初始位置和平移量
                dragStartX = event.getSceneX();
                dragStartY = event.getSceneY();
                initialTranslateX = imageView.getTranslateX();
                initialTranslateY = imageView.getTranslateY();
                event.consume(); // 阻止事件冒泡
            }
        });

        imageView.setOnMouseDragged(event -> {
            if (event.isPrimaryButtonDown()) {
                // 计算偏移量并更新平移
                double deltaX = event.getSceneX() - dragStartX;
                double deltaY = event.getSceneY() - dragStartY;
                imageView.setTranslateX(initialTranslateX + deltaX);
                imageView.setTranslateY(initialTranslateY + deltaY);
                event.consume();
            }
        });
    }

    // EXIF 方向处理
    private void applyOrientationRotation(int orientation) {
        switch (orientation) {
            case 6 -> imageView.setRotate(90);
            case 8 -> imageView.setRotate(270);
            case 3 -> imageView.setRotate(180);
            default -> imageView.setRotate(0);
        }
    }

    // 重置缩放参数
    private void resetZoom() {
        scaleFactor = 1.0;
        imageView.setScaleX(scaleFactor);
        imageView.setScaleY(scaleFactor);
        imageView.setTranslateX(0); // 重置水平平移
        imageView.setTranslateY(0); // 重置垂直平移
        scrollPane.setHvalue(0.5);
        scrollPane.setVvalue(0.5);
    }

    // 导航方法
    @FXML
    private void PreviousPhoto(ActionEvent event) {
        if (imageList != null && currentIndex > 0) {
            currentIndex--;
            currentImageFile = imageList.get(currentIndex);
            loadImage();
            updatePageInfo(); // 更新页数显示
        } else {
            DialogUtils.showInfoDialog("提示", "已经是第一张图片");
        }
    }

    @FXML
    private void NextPhoto(ActionEvent event) {
        if (imageList != null) {
            if (currentIndex < imageList.size() - 1) {
                currentIndex++;
                currentImageFile = imageList.get(currentIndex);
                loadImage();
            } else {
                DialogUtils.showInfoDialog("提示", "已经是最后一张图片");
                // 如果正在自动播放则停止
                if (slideTimeline != null && slideTimeline.getStatus() == Animation.Status.RUNNING) {
                    slideTimeline.stop();
                    SlideShowButton.setText("▶");
                }
            }
            updatePageInfo(); // 更新页数显示
        }
    }

    // 辅助方法
    private String getFileExtension(String filename) {
        int dotIndex = filename.lastIndexOf('.');
        return dotIndex == -1 ? "" : filename.substring(dotIndex);
    }

    private int getImageOrientation(File imageFile) {
        try {
            Metadata metadata = ImageMetadataReader.readMetadata(imageFile);
            for (Directory directory : metadata.getDirectories()) {
                if (directory.containsTag(ExifIFD0Directory.TAG_ORIENTATION)) {
                    return directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
                }
            }
        } catch (Exception e) {
            System.out.println("读取 EXIF 失败：" + e.getMessage());
        }
        return 1; // 默认方向
    }

    @FXML
    public void Close(ActionEvent actionEvent) {
// 获取当前Stage并关闭
        ((Stage) imageView.getScene().getWindow()).close();
    }

    @FXML
    public void StartShow(ActionEvent actionEvent) {
        if (imageList == null || imageList.isEmpty()) return;

        if (slideTimeline != null && slideTimeline.getStatus() == Animation.Status.RUNNING) {
            slideTimeline.stop();
            ((Button) actionEvent.getSource()).setText("▶");
        } else {
            slideTimeline = new Timeline(new KeyFrame(Duration.seconds(3), e -> {
                // 添加循环检测
                if (currentIndex >= imageList.size() - 1) {
                    DialogUtils.showInfoDialog("提示", "已播放到最后一张");
                    slideTimeline.stop();
                    ((Button) actionEvent.getSource()).setText("▶");
                } else {
                    NextPhoto(null);
                }
            }));
            slideTimeline.setCycleCount(Animation.INDEFINITE);
            slideTimeline.play();
            ((Button) actionEvent.getSource()).setText("⏸");
        }
    }

    @FXML
    public void handleScroll(ScrollEvent event) {
        double deltaY = event.getDeltaY();
        if (deltaY == 0) return;

        double zoomFactor = deltaY > 0 ? 1.1 : 0.9;
        scaleFactor = Math.max(0.1, Math.min(5.0, scaleFactor * zoomFactor));
        applyZoom();

        // 调整滚动条位置保持焦点（原有逻辑）
        double mouseX = event.getX();
        double mouseY = event.getY();
        scrollPane.setHvalue(mouseX / imageView.getBoundsInLocal().getWidth());
        scrollPane.setVvalue(mouseY / imageView.getBoundsInLocal().getHeight());
    }

    @FXML
    private void handleZoomOut(ActionEvent event) {
        adjustZoom(0.9);
    }

    @FXML
    private void handleZoomIn(ActionEvent event) {
        adjustZoom(1.1);
    }

    // 缩放方法
    private void adjustZoom(double factor) {
        scaleFactor = Math.max(0.1, Math.min(5.0, scaleFactor * factor));
        applyZoom();
    }

    // 应用缩放方法
    private void applyZoom() {
        imageView.setScaleX(scaleFactor); // 设置水平缩放
        imageView.setScaleY(scaleFactor); // 设置垂直缩放
        ScaleSlider.setValue(scaleFactor); // 更新缩放滑块
    }

    //实现页数更新方法
    private void updatePageInfo() {
        if (imageList != null && !imageList.isEmpty()) {
            pageInfo.setText(String.format("第%d/%d张", currentIndex + 1, imageList.size()));
        } else {
            pageInfo.setText(currentImageFile != null ? "单张图片" : "无图片");
        }
    }
}